package com.andaily.web.controller.mobile;

import com.andaily.domain.dto.user.ForgotPasswordDTO;
import com.andaily.service.UserService;
import com.andaily.web.controller.validator.ForgotPasswordValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author Shengzhao Li
 */
@Controller
@RequestMapping("/login/forgot_password")
public class ForgotPasswordController {

    private UserService userService;
    private ForgotPasswordValidator forgotPasswordValidator;

    @RequestMapping(method = RequestMethod.GET)
    public String setupForm(ModelMap model) {
        model.addAttribute("forgotPasswordDTO", new ForgotPasswordDTO());
        return "mobile_forgot_password";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String submit(@ModelAttribute("forgotPasswordDTO") ForgotPasswordDTO forgotPasswordDTO, BindingResult result, ModelMap model) {
        forgotPasswordValidator.validate(forgotPasswordDTO, result);
        if (result.hasErrors()) {
            return "mobile_forgot_password";
        }
        userService.forgotPassword(forgotPasswordDTO);
        model.addAttribute("email", forgotPasswordDTO.getEmail());
        return "redirect:/m/login/forgot_password/success";
    }


    @RequestMapping("success")
    public String success() {
        return "mobile_forgot_password_success";
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    @Qualifier(value = "forgotPasswordValidator")
    public void setForgotPasswordValidator(ForgotPasswordValidator forgotPasswordValidator) {
        this.forgotPasswordValidator = forgotPasswordValidator;
    }
}
